/* Fixes a bug with jquery-template. When rendering i.e. an <img> with `src` attribute,
* all template placeholders in `src`'s value are escaped which cause the template not to render
* correctly the `src`. This function fixes this bug for <img> and <a>. Just call the function 
* with the rendered template object as first parameter */
function fixRenderedTemplate(rendered){
    var fixArray = [["img", "src"], ["a", "href"]];
    for (var i=0; i<fixArray.length; i++){
        var tagName = fixArray[i][0];
        var attrName = fixArray[i][1];
        $(tagName, rendered).each(function(index, elem){
            var data = $(elem).tmplItem().data;
            var fixTemplate = unescape($(elem).attr(attrName));
            var url = $.tmpl(fixTemplate, data).text();
            $(elem).attr(attrName, url);
        });
    }
}

/* A javascript class for writing "pop-up" like elements which stay when clicking on <$inElem>, but disappear when clicking anywhere else. */
// TODO: destroyed on close ?
function PopUp($elem, $inElem, onClose, atNextClick){
    atNextClick = typeof(atNextClick) != 'undefined' ? atNextClick : false;
    onClose = typeof(onClose) != 'undefined' ? onClose : function(){};
    if (atNextClick) {
        PopUp.prototype.popUps.notInitialized.push(this);
    }
    else {
        PopUp.prototype.popUps.ready.push(this);
    }
    var self = this;
    this.$elem = $elem;
    this.mouseOver = false;
    this.onClose = onClose;
    $inElem.hover(function(){    
        self.mouseOver = true;
    }, function(){
        self.mouseOver = false;
    });
}

PopUp.prototype.popUps = new Array();
PopUp.prototype.popUps.ready = new Array();
PopUp.prototype.popUps.notInitialized = new Array();
PopUp.prototype.initialized = false;
PopUp.prototype.initialize = function(){
    $("body").click(function(){
        var ready = PopUp.prototype.popUps.ready;
        var notInitialized = PopUp.prototype.popUps.notInitialized;
        // handle all <ready> pop-ups
        for (var i=0; i<ready.length; i++){
            if (!ready[i].mouseOver){
                ready[i].onClose();
                ready[i].$elem.addClass("displayNone");
            }
        }
        // initialize all <notInitialized> pop-ups
        for (var i=0; i<notInitialized.length; i++){
            PopUp.prototype.popUps.ready.push(notInitialized.pop(i));
        }
    });
    PopUp.prototype.initialized = true;
}

$(function(){
    PopUp.prototype.initialize();
});


function logout() {

    $.post("/Account" + "/LogOff", null, function (result) {
        document.location = result.href;
    });
    return false;
}

function callWelcome() {
    $("#welcome").show();
}

